package com.tx.weixin.util;


import com.tx.weixin.entity.BaseMessage;
import com.tx.weixin.entity.TextMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtils {
    /**
     * 解析微信发来的请求（xml）
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        //将解析的结果存入map中
        Map<String, String> map = new HashMap<>();
        //获取输入流
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        //得到xml根元素
        Element root = document.getRootElement();
        //获取根元素的所有子节点
        List<Element> elements = root.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getStringValue());
        }

        inputStream.close();
        inputStream = null;
        return map;
    }

    /**
     * 用于处理所有事件的消息回复
     *
     * @param requestMap
     * @return xml数据包
     */
    public static String getRespose(Map<String, String> requestMap) {
        BaseMessage msg = null;
        String msgType = requestMap.get("MsgType");

        switch (msgType) {
            case "text":
                msg = dealTextMessage(requestMap);
                break;
            case "image":

                break;
            case "voice":

                break;
            case "video":

                break;
            case "music":

                break;
            case "news":

                break;
        }
        System.out.println(msg);
        return null;
    }

    /**
     * 处理文本消息
     *
     * @param requestMap
     * @return
     */
    private static BaseMessage dealTextMessage(Map<String, String> requestMap) {
        TextMessage textMsg = new TextMessage(requestMap, "你要干啥");
        return textMsg;
    }
}
